package com.mass.core.sys.file.service.impl;

import com.mass.core.sys.file.dao.FileInfoTempMapper;
import com.mass.core.sys.file.model.FileInfoTemp;
import com.mass.core.sys.file.service.FileUploadService;
import com.mass.core.sys.file.utils.FileUploadUtil;
import com.mass.core.sys.file.utils.ImageScale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 文件上传service实现类</p>
 *
 * @author liwenjun
 * @version 1.0.0
 * @date 2016/11/23 14:15
 */
@Service
public class FileUploadServiceImpl implements FileUploadService{

    private final static Logger LOGGER = LoggerFactory.getLogger(FileUploadService.class);

    @Autowired
    private FileInfoTempMapper fileInfoTempMapper;
    
    @Value("${ueditor.upload-path}")
    private String basePath;    //文件路径
    
    @Value("${server.context-path}")
    private String projectName;   //项目前缀

    /**
     * 文件上传服务器
     * @param request
     * @param type
     * @param code
     * @param isShrink
     * @return
     */
    public List<FileInfoTemp> uploadFile(MultipartHttpServletRequest request, String code, boolean isShrink){
        if(ObjectUtils.isEmpty(code))
        	code = "";
    	List<FileInfoTemp> files = new ArrayList<FileInfoTemp>();
        FileInfoTemp fileInfoTemp = null;
        //build an iterator
        //Iterator<String> itr =  request.getFileNames();
        MultipartFile mpf = null;
        List<MultipartFile> multipartFiles = request.getFiles("file");
        // 获取服务器存储文件路径
        String path = basePath.replaceAll("\\\\","");
        //循环上传文件
        //while(itr.hasNext()){
        for(int i = 0;i<multipartFiles.size();i++){
            //获取MultipartFile
            //mpf = request.getFile(itr.next());
        	mpf = multipartFiles.get(i);
            //获取源文件名
            String originalFileName = mpf.getOriginalFilename();

            //new FileInfoTemp
            fileInfoTemp = new FileInfoTemp();
            fileInfoTemp.setOriginalName(originalFileName);
            fileInfoTemp.setFileSize(String.valueOf(mpf.getSize()/1024)); //单位（kb）
            fileInfoTemp.setFileType(mpf.getContentType());//文件类型

            //生成新文件名
            String basePath = FileUploadUtil.getFileName();
            String newFileName = basePath + originalFileName.substring(originalFileName.indexOf("."));
            try {
                //验证服务器存储路径是否存在，若不存在，则新建文件夹
                path =  (!ObjectUtils.isEmpty(code) && i == 0) ? path + code : path;
                File serFile = new File(path);
                if (!serFile.exists()) {
                    serFile.mkdirs();
                }
                //新文件路径
                String newPath = path + "/" + newFileName;
                //文件相对路径
                String relativePath = (null != code && !Objects.equals("", code)) ? (code + "/" + newFileName) : newFileName;
                
                fileInfoTemp.setNewName(newFileName);
                fileInfoTemp.setRelativePath(projectName+"/fileURL/" + relativePath);
                fileInfoTemp.setFilePath(newPath);
                fileInfoTemp.setBizType(code);

                //将文件复制到文件服务器对应路径下
                FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(newPath));

                //生成缩列图
                if (isShrink) {
                    //缩列图初始宽度
                    int zoomWidth = ImageScale.ZOOM_WIDTH;
                    //计算缩列图长宽
                    BufferedImage bufferImage = ImageIO.read(new File(newPath));
                    int width = bufferImage.getWidth();
                    int height = bufferImage.getHeight();
                    int zoomHeight = Math.round((float) height/width  * zoomWidth);
                    //缩列图名称
                    String newShrinkPath =  basePath + "." + zoomWidth + "x" + zoomHeight +
                            originalFileName.substring(originalFileName.indexOf("."));
                    //缩列图路径
                    String shrinkPath = path + "/" + newShrinkPath;
                    //缩列图相对路径
                    String relativeShrinkPath = (null != code && !Objects.equals("", code)) ? (code + "/" + newShrinkPath) : newShrinkPath;

                    fileInfoTemp.setShrinkPath(shrinkPath);
                    fileInfoTemp.setShrinkRelativePath(projectName+"/fileURL/" + relativeShrinkPath);

                    //生成缩列图
                    ImageScale.resizeFix(new File(newPath), new File(shrinkPath), zoomWidth, zoomHeight);
                }

                //将文件信息插入数据库临时文件表
                this.fileInfoTempMapper.insert(fileInfoTemp);

            } catch (IOException e) {
                LOGGER.error("upload file error!", e);
                return null;
            }
            files.add(fileInfoTemp);
        }

        return files;
    }
}
